// 用于存放Menu信息，以及当前selectKeys,openKeys
export default {
  namespaced: true,
  state(){
    return {
      menuData:[],
      openKeys:[],
      selectedKeys:[],
    }
  },
  getters:{
    menuData(state){
      return state.menuData
    },
    openKeys(state){
      return state.openKeys
    },
    selectedKeys(state){
      return state.selectedKeys
    },
  },
  mutations:{
    setOpenKeys(state, openKeys){
      state.openKeys = openKeys.slice(0)
    },
    setSelectedKeys(state, selectedKeys){
      state.selectedKeys = selectedKeys
    },
    setMenuData(state, menuData){
      state.menuData = menuData
    },
  },
  actions: {
    getMenuItem({state}, params) {
      // 根据fullPath深度搜索，查找 MenuItem
      const menuData = state.menuData
      const fullPath = params.fullPath
      let result
      let searchFunc = (data) => {
        data.forEach(e => {
          if (e.fullPath === fullPath) {
            result = e
          } else if (e.children && e.children.length > 0) {
            searchFunc(e.children) // 递归向下搜索
          }
        })
      }
      searchFunc(menuData)
      return result
    },
    async getMenuInfo({ dispatch }, params) {
      const menuItem = await dispatch('getMenuItem', params)
      const openKeys = menuItem.openKeys
      const result = []
      return new Promise((resolve) => {
        openKeys.forEach(async path => {
          if (path === '/') {
            result.push('首页')
          } else {
            let item = await dispatch('getMenuItem', {
              fullPath: path
            })
            result.push(item.name)
          }
        });
        resolve(result)
      });
    }
  }
}